package snapex.admin.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.ldap.userdetails.LdapUserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import lombok.extern.slf4j.Slf4j;
import snapex.core.model.User;
import snapex.core.security.AuthenticationManagerBuilderDelegate;
import snapex.user.service.IEmployeeInfoService;
import snapex.user.service.IUserService;

@Slf4j
@Controller
public class ViewController {
	@Autowired
	AuthenticationManagerBuilderDelegate builder;
	
	@Autowired
	IEmployeeInfoService employeeHashService;
	
	@Autowired
	IUserService userService;
	
	@Value("${snapex.wechat.enabled}")
	boolean  isWechatEnabled;
		      
	@Value("${snapex.proxy.enabled}")
	private boolean isProxyEnabled;
	
	@Value("${snapex.expenseClient.downloadUrl}")
	String downloadUrl;
		
	@GetMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE)
	public String indexView(ModelMap modelMap) {
		log.debug("****index view****");
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		
		log.debug("***start to get user detail");
		
		User user = builder.getUserDetails(auth.getPrincipal());
		
		log.debug("***complete get user detail");
		
		modelMap.put("user", user);
		
		employeeHashService.createHash(user);
		
		modelMap.put("isWechatEnabled", isWechatEnabled?"Y":"N");
						
		return "home";
	}

	@GetMapping(value = "/admin", produces = MediaType.TEXT_HTML_VALUE)
	public String adminView(ModelMap modelMap) {
		log.debug("****admin view****");
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();

		String userId = "";
		if(auth.getPrincipal() instanceof LdapUserDetails) {
			userId = ((LdapUserDetails)auth.getPrincipal()).getUsername();
		}else {
			userId = ((User)auth.getPrincipal()).getUsername();
		}
				
		try {
			User user = userService.getByUsername(userId);
			
			modelMap.put("user", user);
			
			modelMap.put("isAdminUser", user.isEnabled()?"Y":"N");
		}
		catch(UsernameNotFoundException e) {
			modelMap.put("isAdminUser", "N");	
		}		
		
		modelMap.put("isProxyEnabled", isProxyEnabled?"Y":"N");
		
		modelMap.put("downloadUrl", downloadUrl);
					
		return "dashboard";
	}
	
	@GetMapping(value = "/login", produces = MediaType.TEXT_HTML_VALUE)
	public String loginView() {
		log.debug("****login view*********");
		
		return "login";
	}

	@PostMapping(value = "/login/error", produces = MediaType.TEXT_HTML_VALUE)
	public String loginErrorView(ModelMap modelMap) {
		log.debug("****login error view*********");
			
//		Enumeration<String> names = request.getParameterNames();
//		
//		while(names.hasMoreElements()) {
//			String name = names.nextElement();
//			log.debug("*****name:{}, value={}", name, request.getParameter(name));
//		}
		
		modelMap.put("errorMessage", "Failed to verify your credentials");
		return "login";
	}

	@PostMapping(value = "/logout", produces = MediaType.TEXT_HTML_VALUE)
	public String logoutView(ModelMap modelMap) {
		log.debug("****logout view*********");
		
		modelMap.put("message", "You have been signed out");
		
		return "login";
	}
	
//    @RequestMapping(value="/home")
//    public String home(ModelMap model){
//        model.addAttribute("hello","模版引擎 ");    
//        
//        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//		Employee employee = ldapAuthenticator.getPrincipal(auth.getName());
//		
//		model.put("user", employee);
//		
//    	return "home";
//    } 
	
	@RequestMapping(value="/v/{vname}")
    public String view(@PathVariable("vname") String vname,ModelMap model){
        model.addAttribute("vname",vname);    	
    	return vname;
    } 
	
	@RequestMapping(value="/v/fragment/{vname}")
    public String fragment(@PathVariable("vname") String vname,ModelMap model){
        model.addAttribute("vname",vname);    	
    	return "fragment/"+vname;
    }
}